﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core;
using ZHDJ.Core.Caching;
using ZHDJ.Core.Util;
using ZHDJ.Data.BLL;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.Edu;
using ZHDJ.WebPage.Master;

namespace ZHDJ.Web.Portal.Edu
{
    public partial class PartySubject : UseMorePageMasterPage
    {
        #region  属性
        /// <summary>
        /// 字母数组
        /// </summary>
        public string[] _leter = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" };
        /// <summary>
        /// 测试题数
        /// </summary>
        public const int _testCount = 3;

        /// <summary>
        /// 专题
        /// </summary>
        public string SpecialFlag
        {
            get
            {
                return this.Request["SpecialFlag"] ?? "null";
            }

        }

        /// <summary>
        /// 题目选项（做题前）
        /// </summary>
        private DataSet _TestSubject;
        /// <summary>
        /// 题目选项（做题前）
        /// </summary>
        public DataSet TestSubject
        {
            get
            {
                if (_TestSubject == null)
                {
                    _TestSubject = PartyEduSubject.GetPartyEduSubjectTest(_testCount, SpecialFlag);
                }
                return _TestSubject;
            }
        }

        /// <summary>
        /// 题目选项（做题后）
        /// </summary>
        private DataSet _TestSubject2;
        /// <summary>
        /// 题目选项（做题后）
        /// </summary>
        public DataSet TestSubject2
        {
            get
            {
                return _TestSubject2;
            }
            set
            {
                _TestSubject2 = value;
            }
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLogin(true);
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        #region 数据加载

        public void LoadData()
        {
            //加载题目
            var dv = TestSubject.Tables[0].AsDataView();
            dv.Sort = "ID";
            if (dv.Count != _testCount)
            {
                divbtnsubmit.Visible = false;
                RegisterJs("errorData();");
                return;
            }
            this.rptSubject.DataSource = dv;
            this.rptSubject.DataBind();

            foreach (DataRowView item in dv)
            {
                this.hdSubjectIDs.Value += Convert.ToString(item["ID"]) + ",";
            }
        }

        #endregion


        #region 事件
        /// <summary>
        /// 绑定选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptSubject_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem)
            {
                //加载选项
                var data = e.Item.DataItem;
                Repeater Repeater = e.Item.FindControl("rptOptions") as Repeater;
                HiddenField hiddenField = e.Item.FindControl("hdSubjectID") as HiddenField;

                if (Repeater == null)
                {
                    return;
                }
                if (IsPostBack)
                {
                    //答题后
                    var dataview = TestSubject2.Tables[1].AsDataView();
                    dataview.RowFilter = string.Format("SubjectID='{0}'", hiddenField.Value);
                    Repeater.DataSource = dataview;
                    Repeater.DataBind();
                }
                else
                {
                    //答题前
                    var dataview = TestSubject.Tables[1].AsDataView();
                    dataview.RowFilter = string.Format("SubjectID='{0}'", hiddenField.Value);
                    Repeater.DataSource = dataview;
                    Repeater.DataBind();
                    divRs.Visible = false;
                }

            }
        }

        /// <summary>
        /// 提交测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmitEx_Click(object sender, EventArgs e)
        {

            var subjectIDs = hdSubjectIDs.Value.Trim(',').Split(',');
            if (subjectIDs.Length != _testCount)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "tip", "dataError();", true);
                return;
            }
            //加载数据
            List<TestSubject> test = new List<TestSubject>();
            TestSubject2 = PartyEduSubject.GetPartyEduSubjectTest(subjectIDs);
            foreach (var item in subjectIDs)
            {
                TestSubject subject = new TestSubject();
                subject.SubjectID = item;
                var dataview = TestSubject2.Tables[1].AsDataView();
                dataview.RowFilter = string.Format("SubjectID='{0}'", item);
                foreach (DataRowView op in dataview)
                {
                    // 题目答案选项ID
                    if (Convert.ToBoolean(op["IsAnswer"]))
                    {
                        subject.Answer.Add(Convert.ToString(op["ID"]));
                        hdAnswer.Value += Convert.ToString(op["ID"]) + ",";
                    }
                    //用户提交的答案选项ID
                    if (!string.IsNullOrEmpty(Request.Form[Convert.ToString(op["ID"])]))
                    {
                        subject.Submit.Add(Convert.ToString(op["ID"]));
                        hdSubmit.Value += Convert.ToString(op["ID"]) + ",";
                    }

                }
                dataview.RowFilter = "";
                test.Add(subject);
            }
            if (PartyEduTestRecord.IsTested(CurrentUser.LoginID, test.Select(a => a.SubjectID).ToList()))
            {
                //防止重复提交
                RegisterJs(string.Format("chongfuError('{0}','{1}')", SpecialFlag, Category));
                return;
            }
            //验证答案
            foreach (var item in test)
            {
                if (item.Answer.Count != item.Submit.Count)
                {
                    item.IsRight = false;
                    break;
                }
                //取差集
                var rs = item.Answer.Except(item.Submit);
                item.IsRight = !rs.Any();
            }

            hdAnswer.Value = hdAnswer.Value.Trim(',');
            hdSubmit.Value = hdSubmit.Value.Trim(',');

            divbtnsubmit.Visible = false;//隐藏提交按钮
            bool allright = test.Count(a => a.IsRight) == _testCount;
            litRs.Text = allright ? "全对了,获得1分（每天最多获得3分）" : "没有全对，没有获得积分";
            divRs.Visible = true;
            var dv = TestSubject2.Tables[0].AsDataView();
            dv.Sort = "ID";
            this.rptSubject.DataSource = dv;
            this.rptSubject.DataBind();
            //保存数据
            SaveData(allright,test);
            
        }



        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="IsAnswerAll"></param>
        /// <param name="test"></param>
        private void SaveData(bool IsAnswerAll, List<TestSubject> test)
        {
            PartyEduTestRecord re = new PartyEduTestRecord();
            re.ID = StringHelper.NewID;
            re.IsAnswerAll = IsAnswerAll?1:0;
            re.SpecialId = this.SpecialFlag;
            re.SubimtAuthor= CurrentUser.LoginID;
            re.SubmitTime = DateTime.Now;

            //添加提交记录
            DB.PartyEduTestRecords.Add(re);
            List<PartyEduTestRecordDetail> details = new List<PartyEduTestRecordDetail>();
            
            foreach (var subject in test)
            {
                foreach (var option in subject.Submit)
                {
                    PartyEduTestRecordDetail detail = new PartyEduTestRecordDetail();
                    detail.ID = StringHelper.NewID;
                    detail.IsRight = subject.IsRight;
                    detail.SubjectID = subject.SubjectID;
                    detail.RecordId = re.ID;
                    detail.OptionID = option;
                    details.Add(detail);
                }
            }
            DB.PartyEduTestRecordDetails.AddRange(details);
            var su= DB.SaveChanges() > 0;
            if (IsAnswerAll && su)
            {
                //增加积分
                PartyScoreHelper.Add(() => PartyScoreHelper.AddEduTest(SpecialFlag, CurrentUser.LoginID, re.ID));

            }
        }

        #endregion

        #region 模块菜单
        /// <summary>
        /// 初始化module  如果通过url传参可不设置
        /// </summary>
        protected override void InitModule()
        {
            Module = "PartyTest";
            //Category = "";

        }
        #endregion
    }


    /// <summary>
    /// 处理测试实体
    /// </summary>
    public class TestSubject
    {
        public TestSubject()
        {
            Answer = new List<string>();
            Submit = new List<string>();
        }

        /// <summary>
        /// 题目ID
        /// </summary>
        public string SubjectID { get; set; }
        /// <summary>
        /// 题目答案选项ID
        /// </summary>
        public List<string> Answer { get; set; }

        /// <summary>
        /// 用户提交的答案选项ID
        /// </summary>
        public List<string> Submit { get; set; }

        /// <summary>
        /// 是否做对
        /// </summary>
        public bool IsRight { get; set; }

    }
}